/**
 * Created by chenzheyu on 2017/4/12.
 */
$(function () {
    var submitAjaxdata = {
        name: '',//类别名称
        brandId: '',//品牌主键
        brandName: '',//品牌名称
        displacementId: '',//排量id
        displacement: '',//排量名称
        transmissionId: '',//变速箱id
        transmission: '',//变速箱名称
        seat: '',//座位数
        pregrant: '',//预授额度
        illegalDeposit: '',//违章押金
        discount: '',//折扣
        deductible: '',//不计免赔
        GPSFree: '',//GPS费用
        cap: '',//封顶
        rent: '',//租金
        typeId: '',//车型ID
        proportion: '',//预付现付比例
        hoildayFree: [],//节假日费用
        photos: '',
        refuelingFee: '',//加油费
    };


    var UpLoadingoption = {
        DefaultImage: [],
        UpLimit: 10,
        url: fileUploadUrl,
        onChange: function (e) {
            submitAjaxdata.photos = e.join(",");
        }
    };
    $('.AddImgContent').UpLoading(UpLoadingoption);
    var AddCarType = $('.AddCarType');
    var NavOption = {
        data: [
            {name: '基本信息', action: true},
            {name: '费用设置'}
        ],
        onChange: function (data) {
            var index = data.index;
            var optionItem = $('.optionItem');
            for (var i = 0; i < optionItem.length; i++) {
                (function () {
                    var j = i;
                    optionItem.eq(j).attr('show', false);
                })()
            }
            optionItem.eq(index).attr('show', true);
            $('.Item').css('transform', 'translate(-' + (index * 50) + '%,0)')
        }
    };

    AddCarType.find('.com.ybkj.daijia.server.model.content.Content .NavTop').OrderTabs(NavOption);

    $.ajax({
        url: ctx + '/rentcontent/selectAllProperty',
        data: {},
        type: 'GET',
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                (function () {
                    var index = i;
                    var pid = data[index].id;
                    var labels = $('<label></label>');
                    labels.append('<span class="selectName">' + data[index].propertyName + '</span><span class="pinpai text"></span>');
                    switch (data[index].seq) {
                        case 1:
                            labels.attr('name', 'type');
                            $.ajax({
                                url: ctx + '/rentcontent/selectContentByPid',
                                data: {
                                    pid: pid
                                },
                                type: 'GET',
                                success: function (data) {
                                    var itemOption = {
                                        data: [],
                                        onChange: function (e) {
                                            submitAjaxdata.type = e.text;
                                            submitAjaxdata.typeId = e.val;
                                        }
                                    };
                                    for (var i = 0; i < data.length; i++) {
                                        (function () {
                                            var index = i;
                                            itemOption.data.push({
                                                name: data[index].contentName,
                                                Val: data[index].id
                                            })
                                        })()
                                    }
                                    labels.find('.text').DownPullSelect(itemOption);
                                }
                            });
                            break;
                        case 2:
                            labels.attr('name', 'displacement');
                            $.ajax({
                                url: ctx + '/rentcontent/selectContentByPid',
                                data: {
                                    pid: pid
                                },
                                type: 'GET',
                                success: function (data) {
                                    var itemOption = {
                                        data: [],
                                        onChange: function (e) {
                                            submitAjaxdata.displacement = e.text;
                                            submitAjaxdata.displacementId = e.val;
                                        }
                                    };
                                    for (var i = 0; i < data.length; i++) {
                                        (function () {
                                            var index = i;
                                            itemOption.data.push({
                                                name: data[index].contentName,
                                                Val: data[index].id
                                            })
                                        })()
                                    }
                                    labels.find('.text').DownPullSelect(itemOption);
                                }
                            });
                            break;
                        case 3:
                            labels.attr('name', 'transmission');
                            $.ajax({
                                url: ctx + '/rentcontent/selectContentByPid',
                                data: {
                                    pid: pid
                                },
                                type: 'GET',
                                success: function (data) {
                                    var itemOption = {
                                        data: [],
                                        onChange: function (e) {
                                            submitAjaxdata.transmission = e.text;
                                            submitAjaxdata.transmissionId = e.val;
                                        }
                                    };
                                    for (var i = 0; i < data.length; i++) {
                                        (function () {
                                            var index = i;
                                            itemOption.data.push({
                                                name: data[index].contentName,
                                                Val: data[index].id
                                            })
                                        })()
                                    }
                                    labels.find('.text').DownPullSelect(itemOption);
                                }
                            });
                            break;
                        case 4:
                            labels.attr('name', 'brandName');
                            $.ajax({
                                url: ctx + '/rentcontent/selectContentByPid',
                                data: {
                                    pid: pid
                                },
                                type: 'GET',
                                success: function (data) {
                                    var itemOption = {
                                        data: [],
                                        onChange: function (e) {
                                            submitAjaxdata.brandName = e.text;
                                            submitAjaxdata.brandId = e.val;
                                        }
                                    };
                                    for (var i = 0; i < data.length; i++) {
                                        (function () {
                                            var index = i;
                                            itemOption.data.push({
                                                name: data[index].contentName,
                                                Val: data[index].id
                                            })
                                        })()
                                    }
                                    labels.find('.text').DownPullSelect(itemOption);
                                }
                            });
                            break;
                    }

                    AddCarType.find('.BasicInformation').append(labels)
                })()
            }
        }
    });


    $('.SetFestival .AddAction').AddCopyButton({});
    var label = $('.SetFestivalContent').find('.label .Time');

    function AllTime() {
        label = $('.SetFestivalContent').find('.label .Time');
        if (label) {
            for (var i = 0; i < label.length; i++) {
                (function () {
                    var index = i;
                    label.eq(i).fdatepicker({
                        format: 'yyyy-mm-dd hh:ii',
                        pickTime: true
                    });
                    label.eq(i).on('change', function () {
                        var Titme = $(this).val();
                        var BreakTitme = $().Timestamp.DateTimestamp(Titme);
                        $(this).data('Time', BreakTitme)
                    });

                })()

            }
        }
    }

    AllTime();
    $('.ADDbutton').on('click', function () {
        label = $('<div class="label"></div>').html('' +
            '<div class="labelContent CustomClear">' +
            '<input class="FestivalName" type="text" name="holidaysname" placeholder="节日">' +
            '<div>：</div>' +
            '<input class="BeginTime Time" type="text" name="beginTime" placeholder="开始时间">' +
            '<div>-</div>' +
            '<input class="EndTime Time" type="text" name="endTime" placeholder="结束时间">' +
            '<div>费用</div>' +
            '<input class="Cost" type="number" name="money" placeholder="当前节日费用">' +
            '<div>元/天</div>' +
            '</div>' +
            '<div class="AddAction">' +
            '</div>');

        label.find('.AddAction').AddCopyButton({});
        var beginTime = label.find('input[name="beginTime"]');
        beginTime.datetimepicker({
            format: "yyyy-mm-dd HH:ii",
            language: 'zh-CN',
            showMeridian: true,
            autoclose: true,
            todayBtn: true
        });
        var endTime = label.find('input[name="endTime"]');
        endTime.datetimepicker({
            format: "yyyy-mm-dd HH:ii",
            language: 'zh-CN',
            showMeridian: true,
            autoclose: true,
            todayBtn: true
        });
        beginTime.on('change', function (e) {
            e.stopPropagation();
            var Titme = beginTime.val();
            var BreakTitme = $().Timestamp.DateTimestamp(Titme);
            beginTime.data('Time', BreakTitme);
        });
        endTime.on('change', function (e) {
            e.stopPropagation();
            var Titme = endTime.val();
            var BreakTitme = $().Timestamp.DateTimestamp(Titme);
            endTime.data('Time', BreakTitme);
        });

        $('.SetFestivalContent').append(label);
    });

    $('.CancelButton').on('click', function () {
        window.location.href = ctx + '/rentvehicle/list';
    });

    $('.OkButton').on('click', function () {

        submitAjaxdata.pregrant = $('input[name="pregrant"]').val() || null;
        submitAjaxdata.name = $('input[name="name"]').val() || null;
        submitAjaxdata.illegalDeposit = $('input[name="illegalDeposit"]').val() || null;
        submitAjaxdata.GPSFree = $('input[name="GPSFree"]').val() || null;
        submitAjaxdata.deductible = $('input[name="deductible"]').val() || null;
        submitAjaxdata.cap = $('input[name="cap"]').val() || null;
        submitAjaxdata.rent = $('input[name="rent"]').val() || null;
        submitAjaxdata.seat = $('input[name="seat"]').val() || null;
        submitAjaxdata.refuelingFee = $('input[name="refuelingFee"]').val() || null;


        var submitState = false;
        var holidaysEle = $('.SetFestivalContent .label');
        submitAjaxdata.hoildayFree = [];
        if (holidaysEle.length >= 1) {
            for (var i = 0; i < holidaysEle.length; i++) {
                var holidaysObj = new Object();
                holidaysObj['money'] = holidaysEle.eq(i).find('input[name="money"]').val() || null;
                holidaysObj['beginTime'] = holidaysEle.eq(i).find('input[name="beginTime"]').data('Time') || null;
                holidaysObj['endTime'] = holidaysEle.eq(i).find('input[name="endTime"]').data('Time') || null;
                holidaysObj['name'] = holidaysEle.eq(i).find('input[name="holidaysname"]').val() || null;
                for (key in holidaysObj) {
                    if (holidaysObj[key] == null) {
                        $('body').Overlays({data: {text: '请检查您的节假日费用信息是否填写完整！', state: 'No'}});
                        submitState = false;
                        return
                    }else if(holidaysObj.money<0){
                        $('body').Overlays({data: {text: '节假日租金不能小于0！', state: 'No'}});
                        submitState = false;
                        return
                    }
                }
                submitState = true;
                submitAjaxdata.hoildayFree.push(JSON.stringify(holidaysObj));
            }
        }
        submitAjaxdata.hoildayFree = submitAjaxdata.hoildayFree.join(",");

        submitAjaxdata.hoildayFree = '[' + submitAjaxdata.hoildayFree + ']';
        for (key in submitAjaxdata) {
            if (!submitAjaxdata[key] == '' && submitAjaxdata[key]) {
                submitState = true;
            } else if (submitAjaxdata['hoildayFree'].length <= 0) {
                submitState = true;
            } else if (key == 'discount') {
                if ($('input[name="discount"]').val()) {
                    if (parseInt($('input[name="discount"]').val()) <= 100) {
                        submitAjaxdata.discount = $('input[name="discount"]').val();
                    } else {
                        $('body').Overlays({data: {text: "请填写在线预订折扣！并且必须在100%内！", state: 'No'}});
                        return;
                    }
                } else {
                    $('body').Overlays({data: {text: '请检查信息是否填写完整！', state: 'No'}});
                    submitAjaxdata.discount = null;
                }
            } else if (key == 'proportion') {
                if ($('input[name="advance"]').val()) {
                    if (parseInt($('input[name="advance"]').val()) <= 100) {
                        submitAjaxdata.proportion = $('input[name="advance"]').val();
                    } else {
                        $('body').Overlays({data: {text: "请填写门店预付比例！并且必须在100%内！", state: 'No'}});
                        return;
                    }
                } else {
                    $('body').Overlays({data: {text: '请检查信息是否填写完整！', state: 'No'}});
                    submitAjaxdata.proportion = null;
                }
            } else if (key == 'photos') {
            } else {
                $('body').Overlays({data: {text: '请检查信息是否填写完整！', state: 'No'}});

                console.error(key, submitAjaxdata[key]);
                submitState = false;
                return;
            }
        }


        if (submitState) {
            $.ajax({
                url: ctx + '/rentvehicle/insertVehicle',
                data: submitAjaxdata,
                type: 'POST',
                success: function (data) {
                    if (data.message == '车系创建成功') {
                        $('body').Overlays({data: {text: '车系创建成功，即将跳转页面！', state: "Ok"}});
                        setInterval(function () {
                            window.location.href = ctx + '/rentvehicle/list';
                        }, 2000);
                    } else {
                        $('body').Overlays({data: {text: '创建失败，请稍后重试！', state: 'No'}})
                    }
                }
            })
        }

    });

    for(var i=0;i<$('input[type="number"]').length;i++){
        (function () {
            var index=i;
            $('input[type="number"]').eq(index).on('change',function () {
                if($(this).val()<0){
                    $(this).val(0)
                }
            })
        })()
    }
});